package ms.platform.util;

import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
 * Map转JavaBean
 * @author Administrator
 *
 */
public class MapToBeanUtils {
   public static <T> T mapToBean(Map<String, Object> map, Class<T> obj) throws Exception {  
        if (map == null) {  
            return null;  
        }  
        Set<Entry<String, Object>> sets = map.entrySet();  
        T t = obj.newInstance();  
        Method[] methods = obj.getDeclaredMethods();  
        for (Entry<String, Object> entry : sets) {  
            String str = entry.getKey();  
            String setMethod = "set" + str.substring(0, 1).toUpperCase() + str.substring(1);  
            for (Method method : methods) {  
                if (method.getName().equals(setMethod)) {
                	Object value = map.get(str);
                	
                    method.invoke(t, entry.getValue());  
                	//method.invoke(t, value);  
                }  
            }  
        }  
        return t;  
    }  
   
   /** 
    * 方法名称:transMapToString 
    * 传入参数:map 
    * 返回值:String 形如 username'chenziwen^password'1234 
   */  
   public static String transMapToString(Map map){  
     java.util.Map.Entry entry;  
     StringBuffer sb = new StringBuffer();  
     for(Iterator iterator = map.entrySet().iterator(); iterator.hasNext();)  
     {  
         entry = (java.util.Map.Entry)iterator.next();  
         sb.append(entry.getKey().toString()).append( ":" ).append(null==entry.getValue()?"":  
         entry.getValue().toString()).append (iterator.hasNext() ? "," : "");  
     }  
     return sb.toString();  
   }  
   
   
   
}
